package routers

import (
	"context"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
	"webdemo/src/gin/base"
	"webdemo/src/gin/base/middleware"
	"webdemo/src/gin/controller"
	utis "webdemo/src/gin/utils"
)

func Run() {

	var router = gin.Default() // 默认使用了 logger 和 recovery 中间件
	// 使用全局中间件
	// 耗时统计
	router.Use(middleware.UseTime)
	// 全局异常处理
	router.Use(base.Recover)

	testGroup := router.Group("/test")
	{
		testGroup.POST("/user/register", controller.UserRegister)
		// 文件上传
		testGroup.POST("/file/upload", controller.FileUpload)

		testGroup.Any("/user", func(ctx *gin.Context) {
			switch ctx.Request.Method {
			case http.MethodGet:
			case http.MethodDelete:
			}
		})
	}

	redisGroup := router.Group("/redis")
	{
		//http://localhost:8080/redis/set/name/zw
		redisGroup.GET("/set/:key/:value", controller.SetValue)
		//http://localhost:8080/redis/get/name
		redisGroup.GET("/get/:key", controller.GetValue)

	}

	redirectGroup := router.Group("/redirect")
	{
		// http://localhost:8080/redirect/index
		// 重定向
		redirectGroup.GET("/index", func(context *gin.Context) {
			context.Redirect(http.StatusMovedPermanently,
				"http://www.baidu.com")
		})
		redirectGroup.GET("/a", func(ctx *gin.Context) {
			ctx.Request.URL.Path = "/redirect/b"
			router.HandleContext(ctx)
		})
		redirectGroup.GET("/b", func(ctx *gin.Context) {
			ctx.JSON(http.StatusOK, gin.H{
				"success": true,
				"msg":     "/b",
			})
		})
	}

	userGroup := router.Group("/user")
	{
		//http://localhost:8080/user/insert
		userGroup.POST("/insert", controller.UserInsert)
		userGroup.POST("/batchInsert", controller.UserBatchInsert)

		userGroup.GET("/queryUserById", controller.QueryUserById)
		userGroup.POST("/queryUserList", controller.QueryUserList)
		userGroup.GET("/queryAllUser", controller.QueryAllUser)
		userGroup.POST("/update", controller.Update)
		userGroup.PUT("/batchUpdate", controller.BatchUpdate)
		userGroup.DELETE("/delete", controller.Delete)
		userGroup.POST("/exeSql", controller.ExeSql)
	}

	/*err := router.Run()
	if err != nil {
		log.Println("router.Run error : ", err)
	}*/

	server := &http.Server{
		Addr:    ":8081",
		Handler: router,
	}

	go func() {
		//注册服务
		utis.ConsulRegister()

		// service connections
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := server.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	utis.ConsulCancelRegister()
	log.Println("Server exiting")
}
